package com.bookstore.controller;

import com.alibaba.fastjson.JSON;
import com.bookstore.entity.User;
import com.bookstore.service.UserService;
import com.bookstore.utils.Json;
import com.bookstore.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 更新用户的头像
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/user/change_headimg", method = RequestMethod.POST)
    @ResponseBody
    public Json changeUserheaderImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Json json = new Json();
        User user = (User) request.getSession().getAttribute(LoginAndRegisterController.USER);
        String filename = file.getOriginalFilename();
        String prefix = filename.substring(filename.lastIndexOf(".") + 1);
        if (prefix.equals("jpg") || prefix.equals("png")) {
            //头像的保存路径
            String savePath = request.getSession().getServletContext().getRealPath("/images/headimg") +"/"+ user.getAccount()+"."+prefix;
            System.out.println(savePath);
            try {
                File file1 = new File(savePath);
                if (file1.exists()){
                    file1.delete();
                }
                file.transferTo(new File(savePath));
                //将头像地址写入数据库
                user.setPhoto(user.getAccount()+"."+prefix);
                if (userService.updateUser(user)){
                    json.setSuccess(true);
                }else {
                    json.setMsg("上传头像失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                json.setMsg("上传出错！");
                json.setSuccess(false);
            }
        } else {
            json.setSuccess(false);
            json.setMsg("您上传的头像格式不正确，我们只支持jpg和png格式的头像");
        }
        return json;
    }

    /**
     * 修改用户信息
     * @return
     */
    @RequestMapping(value = "/user/change_info", method = RequestMethod.POST)
    @ResponseBody
    public Json updateUser(@RequestParam("nickname") String nickname,@RequestParam("email") String email,
                           HttpServletRequest request){
        Json json = new Json();
        User user= (User) request.getSession().getAttribute(LoginAndRegisterController.USER);
        try {
            user.setEmial(email);
            user.setNickname(nickname);
            userService.updateUser(user);
            json.setSuccess(true);
            json.setMsg("修改成功！");
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("修改失败，请检查你的修改信息是否符合要求");
        }
        return json;
    }

    /**
     * 用户修改密码
     * @param oldPasswrod 旧密码
     * @param newPasswrod 新密码
     * @return
     */
    @RequestMapping(value = "/user/alter_user_password",method = RequestMethod.POST)
    @ResponseBody
    public Json modifyUserPassword(@RequestParam("oldPassword") String oldPasswrod,
                                   @RequestParam("newPassword") String newPasswrod,HttpServletRequest request){
        Json json = new Json();
        User user = (User) request.getSession().getAttribute(LoginAndRegisterController.USER);
        if (MD5Util.md5(oldPasswrod).equals(user.getPassword())){
            user.setPassword(MD5Util.md5(newPasswrod));
            userService.updateUser(user);
            json.setSuccess(true);
            json.setMsg("修改成功");
        }else {
            json.setMsg("你输入的旧密码不正确!");
        }
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/get_user",method = RequestMethod.GET,produces = "text/html; charset=UTF-8")
    public String getUser(HttpServletRequest request){
        User user  = (User) request.getSession().getAttribute(LoginAndRegisterController.USER);
        if (user!=null){
            Map<String,String> userInfo = new HashMap<>();
            userInfo.put("account",user.getAccount());
            userInfo.put("photo",user.getPhoto());
            userInfo.put("nickname",user.getNickname());
            userInfo.put("email",user.getEmial());
            return JSON.toJSON(userInfo).toString();
        }else{
            return "您未登录";
        }
    }

    @ResponseBody
    @RequestMapping(value = "log_out",method = RequestMethod.POST)
    public String logOut(HttpServletRequest request){
        try {
            request.getSession().removeAttribute(LoginAndRegisterController.USER);
            return "SUCCESS";
        }catch (Exception e){
            return "ERROR";
        }
    }

    /**
     * 用户退出登录
     * @param request
     * @return
     */
    @RequestMapping(value = "/user/log_out",method = RequestMethod.GET)
    public String UserLogout(HttpServletRequest request){
        request.getSession().removeAttribute(LoginAndRegisterController.USER);
        return "redirect:/jsp/index.jsp";
    }

    /**
     * 调到私人推荐页面
     * @return
     */
    @RequestMapping(value = "/user/recommend",method = RequestMethod.GET)
    public String userRecommend(){
        return "redirect:/jsp/recommend.jsp";
    }

}
